package com.example.demo.Controler.UserController;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

import static com.example.demo.Errno.ErrnoDef.ERRNO_NOT_LOGGED_IN;
import static com.example.demo.Errno.ErrnoDef.ERRNO_SUCCESS;

/**
 * 需要登录后才可访问的api的控制类 <br>
 * “/secure/*”的内容会先经过过滤器，获取token的用户信息 {@link com.example.demo.Filter.JwtFilter}
 */
@RestController
public class UserInfoController {

    private final Logger logger = LoggerFactory.getLogger(UserInfoController.class);

    /**
     * 查询当前用户信息(需登录) (这个接口暂时用于测试)
     * @param request 请求对象
     * @return json串（字典），键值对：<br>
     * - errno：错误码 (0为无错误)<br>
     * - msg：错误信息 <br>
     * - data：字典对象，键值对包括当前用户的id和用户名
     */
    @RequestMapping("/api/getUserInfo")
    public  Map<String,Object> getUserInfo(HttpServletRequest request){
        Map<String,Object> resmap = new HashMap<>();
        Map<String,Object> datamap = new HashMap<>();
        Integer userid = (Integer) request.getAttribute("id");
        if(userid == null){
            resmap.put("errno", ERRNO_NOT_LOGGED_IN.getErrno());
            resmap.put("msg", ERRNO_NOT_LOGGED_IN.getMsg());
            resmap.put("data",datamap);
            return resmap;
        }

        String name = request.getAttribute("name").toString();

        datamap.put("id",userid);
        datamap.put("name",name);
        resmap.put("errno", ERRNO_SUCCESS.getErrno());
        resmap.put("msg","查询成功");
        resmap.put("data",datamap);
        return resmap;
    }
}
